import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import axios from "axios";
interface HomeState {
  loading: boolean;
  data: ListItem[];
}

export interface ListItem {
  title: string;
  id: string;
  desc: string;
  url: string;
  price: number;
}

const initialState: HomeState = {
  loading: true,
  data: [],
};

export const fetchHomeData = createAsyncThunk(
  "home/fetchHomeData",
  async () => {
    const resp = await axios.get("/api/list");
    return resp.data;
  }
);

const homeSlice = createSlice({
  name: "home",
  initialState,
  reducers: {},
  // extraReducers: {
  //   [fetchHomeData.pending.type](state) {
  //     state.loading = true;
  //   },
  //   [fetchHomeData.fulfilled.type](state, action) {
  // state.loading = false;
  // state.data = action.payload.data;
  //   },
  // },
  extraReducers(builder) {
    builder.addCase(fetchHomeData.pending, (state) => {
      state.loading = true;
    });

    builder.addCase(fetchHomeData.fulfilled, (state, action) => {
      state.loading = false;
      state.data = action.payload.data;
    });
  },
});

export default homeSlice;
